package com.zhou.bjgl.bjgl.business_web.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.zhou.bjgl.bjgl.req.user.UserReq;
import com.zhou.bjgl.bjgl.resp.user.BUserForInfoResp;
import com.zhou.bjgl.bjgl.business_web.service.CommonService;
import com.zhou.bjgl.bjgl.business_web.service.TokenService;
import com.zhou.bjgl.bjgl.util.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: TokenServiceImpl
 * @Description:
 * @Author: zhou
 * @Date: 2022/2/25 12:20
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Resource
    private CommonService commonService;

    @Resource
    private RedisUtil redisUtil;
    /**
     * 生成token
     * @param req
     * @return
     */
    @Override
    public String getToken(UserReq req) {
        BUserForInfoResp userInfo = commonService.getUserInfo(req);
        // token的生成方法
        // Algorithm.HMAC256():使用HS256生成token,密钥则是用户的密码，唯一密钥的话可以保存在服务端。
        // withAudience()存入需要保存在token的信息，这里我把用户ID存入token中
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,120);
        String token="";
        token = JWT.create()
                .withClaim("name",userInfo.getName())//pyload
                .withClaim("className",userInfo.getClassName())
                .withClaim("classId",userInfo.getClassId())
                .withClaim("collegeId",userInfo.getCollegeId())
                .withClaim("power",userInfo.getPower())
                .withClaim("username",userInfo.getUsername())
                .withClaim("id",userInfo.getId())
                .withClaim("email",userInfo.getEmail())
                .withClaim("profile_url",userInfo.getProfileUrl())
                .withClaim("phone",userInfo.getPhone())
                .withExpiresAt(instance.getTime())//设置过期时间
                .withAudience(userInfo.getUsername()).sign(Algorithm.HMAC256(userInfo.getPassword()));
        redisUtil.set(userInfo.getUsername(),token,6000);
        return token;
    }
}
